#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <unordered_map>
#include "Log.hpp"

using namespace std;

using func_t = function<string(const string &, const string &, uint16_t &)>;

enum
{
    SOCKERR,
    BDERR
};

Log lg;
const int size = 1024;

class Server
{
public:
    Server(const uint16_t &port, const string &ip) : _port(port), _ip(ip)
    {
    }

    void Init()
    {
        //1.创建udp
        //2.udp的socket是全双工的，允许被同时读写
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg(Fatal, "scokfd create fail : %d", _sockfd);
            exit(SOCKERR);
        }
        lg(Info, "socket create success,sockfd: %d", _sockfd);

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;                     // 声明结构体是IPV4家族
        local.sin_port = htons(_port);                  // 将端口号从主机转网络
        local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 将ip地址转整数

        int n = bind(_sockfd, (sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            lg(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BDERR);
        }
        lg(Info, "bind success");
    }

    void CheckUser(struct sockaddr_in &client, const string &clientip, uint16_t &clientport)
    {
        auto iter = _onlineuser.find(clientip);
        if (iter == _onlineuser.end())
        {
            _onlineuser.insert({clientip, client});
            cout << "[" << clientip << ": " << clientport << "]@ add a online user, welcome~~~" << endl;
        }
    }

    void Broadcast(const string &info, const string &clientip, uint16_t &clientport)
    {
        for (const auto &user : _onlineuser)
        {
            string message = "["+clientip+":"+to_string(clientport)+"]$"+info;
            socklen_t len = sizeof(user.second);
            sendto(_sockfd, message.c_str(), message.size(), 0, (sockaddr*)&user.second,len);
        }
    }

    void Run()
    {
        while (_isrunning)
        {
            char inbuffer[size];
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t s = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (sockaddr *)&client, &len);
            if (s < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            uint16_t clientport = ntohs(client.sin_port); // 将客户端的端口号网络转主机
            string clientip = inet_ntoa(client.sin_addr); // 将四字节ip地址转字符串
            CheckUser(client, clientip, clientport);
            string info = inbuffer;
            Broadcast(info, clientip, clientport);

            // inbuffer[s] = 0;
        }
    }

    ~Server()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }

private:
    int _sockfd = 0;
    uint16_t _port;
    string _ip;
    bool _isrunning = true;
    unordered_map<string, struct sockaddr_in> _onlineuser;
};